package com.lwk.web.interceptor;

import java.util.List;
import java.util.Map;

import com.lwk.domain.Admin;
import com.lwk.service.impl.AdminServiceImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import org.apache.struts2.StrutsStatics;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class LoginInterceptor extends MethodFilterInterceptor {
    private AdminServiceImpl adminService;
    //指定不拦截登陆方法. 其他方法都拦截

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {

        //1.获得session
        Map<String, Object> session = ActionContext.getContext().getSession();
        //2.获得登陆标识
        Object object = session.get("user");
        //3.判断登陆标识是否存在
        if (object == null) {
            //不存在=>没登录=>重定向到登录页面
            HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
            Cookie[] cks = request.getCookies();
            for (Cookie cookie : cks) {
                if ("user".equals(cookie.getName())) {
                    String username = cookie.getValue().split("-")[0];
                    System.out.println(username);
                    String password = cookie.getValue().split("-")[1];
                    System.out.println(password);
                    DetachedCriteria dc = DetachedCriteria.forClass(Admin.class);
                    dc.add(Restrictions.eq("username", username));
                    dc.add(Restrictions.eq("password", password));
                    List<Admin> list =  adminService.login(dc);
                    if (list.size() != 0) {
                        ActionContext.getContext().getSession().put("user", list.get(0));
                        return "index";
                    } else {
                        return "toLogin";
                    }
                }
            }
            return "toLogin";
        } else {
            //存在=>已经登陆=>放行
            return invocation.invoke();
        }
    }

    public void setAdminService(AdminServiceImpl adminService) {
        this.adminService = adminService;
    }

}
